/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年05月22日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <map>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
private:
    map<TreeNode*, int>m;
    map<TreeNode*, int>::iterator it;

public:
    int rob(TreeNode* root) {
        if( root == NULL )
            return 0;
        if( (it = m.find(root)) != m.end() ){
            return it->second;
        }

        int maxleft = 0, maxright = 0;
        int maxres = 0;

        int maxlleft = 0, maxrrght = 0;
        if(root->left){
            maxleft = rob(root->left);
            maxlleft = rob(root->left->left) + rob(root->left->right);
        }
        if(root->right){
            maxright = rob(root->right);
            maxrrght = rob(root->right->left) + rob(root->right->right);
        }

        maxres = max(maxres, maxlleft + maxrrght + root->val);
        maxres = max(maxres, maxleft+maxright);

        m.insert(it, pair<TreeNode*, int>(root, maxres));
        return maxres;
    }
};
